package com.jinmei.pushclient;

import java.util.Map;

import org.apache.log4j.Logger;

import com.jinmei.service.JPushAliasService;
import com.jinmei.utils.JinmeiConsts;
import com.jinmei.utils.ResourceManager;
import com.jinmei.utils.StringUtil;
import com.jinmei.web.ws.NotificationMessage;

import cn.jpush.api.DeviceEnum;
import cn.jpush.api.ErrorCodeEnum;
import cn.jpush.api.JPushClient;
import cn.jpush.api.MessageResult;

public class PushClientProxy {
	
	private static Logger logger = Logger.getLogger(PushClientProxy.class);
	private static JPushClient jpush =new JPushClient( 
					ResourceManager.getValue(JinmeiConsts.JPUSH_MASTER_SECRET),
					ResourceManager.getValue(JinmeiConsts.JPUSH_APPKEY), 
					StringUtil.toLong(ResourceManager.getValue(JinmeiConsts.JPUSH_TIME_TO_LIVE), 0),
					DeviceEnum.Android);
	
	private JPushAliasService aliasService;
	public JPushAliasService getAliasService() {
		return aliasService;
	}
	public void setAliasService(JPushAliasService aliasService) {
		this.aliasService = aliasService;
	}

	public MessageResult sendMessageToAll(String msgTitle, String msgContent) {
		MessageResult msgResult = jpush.sendNotificationWithAppKey(getRandomSendNo(), msgTitle, msgContent);
		printLog(msgResult);
		return msgResult;
	}
	
	public MessageResult sendMessageToUser(String msgTitle, String msgContent, Long employeeId) {
		MessageResult msgResult = jpush.sendNotificationWithAlias(getRandomSendNo(), getAliasByEmployee(employeeId), msgTitle, msgContent);
		printLog(msgResult);
		return msgResult;
	}
	
	public void sendMessagesToMany(Map<Integer, NotificationMessage> msgs) {
		
	}
	
	private String getAliasByEmployee(Long employeeId) {
		return getAliasService().getAliasByEmployee(employeeId);
	}
	
	private void printLog(MessageResult msgResult) {
		if (null != msgResult) {
			if (msgResult.getErrcode() == ErrorCodeEnum.NOERROR.value()) {
				logger.info("Send succeed， sendNo=" + msgResult.getSendno());
			} else {
				logger.info("Send failed， error code=" + msgResult.getErrcode() + ", error msg=" + msgResult.getErrmsg());
			}
		} else {
			logger.info("Cannot get message data");
		}
	}

	/**
	 * It is very important to keep sendNo unique.
	 * @return sendNo
	 */
	public static int getRandomSendNo() {
		return (int) (JinmeiConsts.MIN + Math.random() * (JinmeiConsts.MAX - JinmeiConsts.MIN));
	}

}
